<template>
    <div>
        <fullscreenModal :modal="showModal" :label="showPayModal ? '我的订单' : '我的购物车'" :isShowEdit="false" :showSave="false" editType="other" @handleClose="handleClose()">
            <p class="myBtn" v-if="!showPayModal">
                <van-icon name="replay" @click="getCarData()" />
            </p>
            <template v-if="!showPayModal">
                <div class="orderContent">
                    <van-checkbox-group v-model="checkAllGroup">
                        <div v-for="(item, index) in carList" :key="item.rowId" class="list-item" :class="item.type === 'canteen' ? 'list-head' : ''">
                            <div v-if="item.type === 'canteen'" class="head">
                                <van-checkbox :name="item.rowId" :disabled="item.code !== '1'">
                                    <div class="flexRow head-item">
                                        <p><b>{{item.canteenName}}</b>（ {{item.cookbookDate}} ）</p>
                                        <span>{{item.mealsTypeName}}</span>
                                    </div>
                                </van-checkbox>
                            </div>
                            <div v-else-if="item.type === 'invalid'" class="flexRow">
                                <van-checkbox disabled></van-checkbox>
                                <img :src="fileUrlObj[item.filecode] || (loading ? 'images/loading.gif' : 'images/noImgData.png')">
                                <div class="con">
                                    <div class="flexRow dishName">
                                        <p>{{item.dishName}}</p>
                                        <span :class="item.msg !== '正常' ? 'other' : ''">{{item.msg}}</span>
                                    </div>
                                    <div class="flexRow priceNum">
                                        <p>
                                            <span>限购：{{item.dishLimitAmount === '-1' ? '不限购' : item.dishLimitAmount}}</span>
                                            <span>供应：{{item.supplyAmount}}</span>
                                        </p>
                                        <p class="price">￥{{item.discountPrice}}</p>
                                    </div>
                                    <div class="flexRow action">
                                        <div></div>
                                        <a @click="handleDelete(item)">删除</a>
                                    </div>
                                </div>
                            </div>
                            <div v-else class="flexRow">
                                <van-checkbox :name="item.rowId"></van-checkbox>
                                <img :src="fileUrlObj[item.filecode] || (loading ? 'images/loading.gif' : 'images/noImgData.png')">
                                <div class="con">
                                    <div class="flexRow dishName">
                                        <p>{{item.dishName}}</p>
                                        <span>{{item.msg}}</span>
                                    </div>
                                    <div class="flexRow priceNum">
                                        <p>
                                            <span>限购：{{item.dishLimitAmount === '-1' ? '不限购' : item.dishLimitAmount}}</span>
                                            <span>供应：{{item.supplyAmount}}</span>
                                        </p>
                                        <p class="price">￥{{item.discountPrice}}</p>
                                    </div>
                                    <div class="flexRow action">
                                        <van-stepper v-model="carList[index].dishNum" class="stepBox" integer min="1" :max="item.dishLimitAmount ? Math.min(item.supplyAmount, item.dishLimitAmount) : item.supplyAmount" @change="changeNumber(index)" />
                                        <a @click="handleDelete(item)">删除</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <van-empty v-if="!spinLoading && !carList.length" class="custom-image" :image="require('../../../../assets/images/empty.png')" description="暂无数据" />
                    </van-checkbox-group>
                    <div class="bottomTip">
                        <van-submit-bar :price="totalPrice * 100" :suffix-label="'(已选' + selectedData.length + '件)'" button-text="结算" :disabled="!checkAllGroup.length" @submit="handlePayment">
                            <van-checkbox v-model="checkAll" @click="handleCheckAll" :disabled="!effectiveList.length">全选</van-checkbox>
                        </van-submit-bar>
                    </div>
                </div>
            </template>
            <template v-else>
                <payComp ref="payCompRef" @closeAll="handleClose()" @close="showPayModal = false" @refresh="getCarData()"></payComp>
            </template>
        </fullscreenModal>
        <full-loading v-if="spinLoading"></full-loading>
    </div>
</template>

<script>
    import payComp from './payComp';
    import { queryFileList } from '@/api/common';
    import { getCartInByLoginUser, settlementCart, editNumAddAndDel, delCart } from '@/api/srvAssurance/smarcatering/takeawayOrder';
    export default {
        name: 'myCar',
        components: { payComp },
        data () {
            return {
                showModal: false,
                showPayModal: false,
                spinLoading: false,
                loading: false,
                totalPrice: 0,
                carList: [],
                effectiveList: [],
                checkAll: false,
                checkAllGroup: [],
                fileUrlObj: {},
                cancelId: ''
            }
        },
        computed: {
            selectedData: function () {
                return this.checkAllGroup.filter(item => item.indexOf('**') !== -1)
            }
        },
        watch: {
            checkAllGroup: function (val, oldVal) {
                if (val.length) {
                    let flag = false;
                    let _newArr = [...val];
                    if (val.length > oldVal.length) { // 选中
                        this.cancelId = '';
                        val.forEach(item => {
                            if (oldVal.indexOf(item) === -1) {
                                let _data = this.effectiveList.filter(_newArr => item === _newArr.rowId)[0];
                                // 选中食堂复选框（所属菜肴全部选中）
                                if (item.indexOf('**') === -1 && _data.type === 'canteen') {
                                    _data.data.forEach(v => {
                                        let rowId = v.cookbookId + '**' + v.dishId;
                                        if (_newArr.indexOf(rowId) === -1) {
                                            flag = true;
                                            _newArr.push(rowId);
                                        }
                                    })
                                } else { // 选中菜肴复选框（判断所属食堂是否应选中）
                                    let cookbookId = _data.cookbookId;
                                    let _arr = this.effectiveList.filter(j => j.cookbookId === cookbookId && j.type === 'canteen');
                                    let rowIdPre = _data.cookbookId + "**";
                                    if (_arr[0].data.length === _newArr.filter(k => k.indexOf(rowIdPre) !== -1).length && _newArr.indexOf(_data.cookbookId) === -1) {
                                        flag = true;
                                        _newArr.push(cookbookId);
                                    }
                                }
                            }
                        })
                    } else { // 取消
                        oldVal.forEach(item => {
                            if (_newArr.indexOf(item) === -1) {
                                let _data = this.effectiveList.filter(_newArr => item === _newArr.rowId)[0];
                                if (this.cancelId === _data.cookbookId) {
                                    return
                                }
                                // 取消食堂复选框（所属菜肴全部取消）
                                if (item.indexOf('**') === -1 && _data.type && _data.type === 'canteen') {
                                    _data.data.forEach(v => {
                                        let rowId = v.cookbookId + '**' + v.dishId;
                                        let _ind = _newArr.indexOf(rowId);
                                        if (_ind !== -1) {
                                            flag = true;
                                            _newArr.splice(_ind, 1);
                                        }
                                    })
                                } else { // 取消菜肴复选框（所属食堂取消）
                                    let _ind = _newArr.indexOf(_data.cookbookId);
                                    if (_ind !== -1) {
                                        flag = true;
                                        this.cancelId = _data.cookbookId;
                                        _newArr.splice(_ind, 1);
                                    }
                                }
                            }
                        })
                    }
                    if (flag) {
                        this.checkAllGroup = _newArr;
                    }
                }
                if (this.checkAllGroup.length && this.checkAllGroup.length === this.effectiveList.length) {
                    this.checkAll = true;
                } else {
                    this.checkAll = false;
                }
                this.getTotalPrice();
            }
        },
        methods: {
            openMyCar () {
                this.showModal = true;
                this.getCarData();
            },
            handleClose () {
                if (this.showPayModal) {
                    this.showPayModal = false;
                    this.getCarData();
                } else {
                    this.showModal = false;
                    this.$emit('refresh');
                }
            },
            // 查询购物车列表
            getCarData () {
                this.totalPrice = 0;
                this.carList = [];
                this.effectiveList = [];
                let filecodeArr = [];
                this.checkAll = false;
                this.checkAllGroup = [];
                this.spinLoading = true;
                getCartInByLoginUser().then(res => {
                    this.spinLoading = false;
                    if (res.code === 1000 && res.data) {
                        res.data.forEach(item => {
                            let _codeArr = item.data.filter(item => item.code === '1');
                            if (_codeArr.length) { // 有正常状态的食堂菜肴
                                this.carList.push({
                                    type: 'canteen',
                                    code: '1',
                                    rowId: item.cookbookId,
                                    ...item
                                })
                                this.effectiveList.push({
                                    type: 'canteen',
                                    code: _codeArr.length ? '1' : '999',
                                    rowId: item.cookbookId,
                                    canteenId: item.canteenId,
                                    canteenName: item.canteenName,
                                    cookbookDate: item.cookbookDate,
                                    cookbookId: item.cookbookId,
                                    isSeckill: item.isSeckill,
                                    mealsType: item.mealsType,
                                    mealsTypeName: item.mealsTypeName,
                                    data: _codeArr
                                })
                            } else {
                                this.carList.push({
                                    type: 'canteen',
                                    code: '999',
                                    rowId: item.cookbookId,
                                    ...item
                                })
                            }
                            item.data.forEach(val => {
                                if (_codeArr.length && val.code === '1') {
                                    this.effectiveList.push({
                                        type: 'dish',
                                        rowId: val.cookbookId + '**' + val.dishId,
                                        ...val
                                    })
                                }
                                this.carList.push({
                                    type: val.code === '1' ? 'dish' : 'invalid',
                                    rowId: val.cookbookId + '**' + val.dishId,
                                    ...val
                                });
                                if (val.filecode && !this.fileUrlObj[val.filecode]) {
                                    filecodeArr.push(val.filecode);
                                    this.fileUrlObj[val.filecode] = '';
                                }
                            })
                        })
                        if (filecodeArr.length) {
                            this.queryFileInfoData(filecodeArr);
                        }
                    }
                }).catch(() => {
                    this.spinLoading = false;
                })
            },
            // 全选
            handleCheckAll () {
                this.checkAllGroup = [];
                if (this.checkAll) {
                    this.effectiveList.forEach(item => {
                        this.checkAllGroup.push(item.rowId);
                    })
                }
            },
            // 改变菜肴数量
            changeNumber (index) {
                let item = this.carList[index];
                if (!this.carList[index].dishNum) {
                    this.carList[index].dishNum = 1;
                }
                let params = {
                    cartId: item.cartId,
                    dishNum: item.dishNum
                }
                editNumAddAndDel(params).then(res => {
                    if (res.code === 1000) {
                        this.getTotalPrice();
                    }
                })
            },
            // 计算总价
            getTotalPrice () {
                this.totalPrice = 0;
                if (this.checkAllGroup.length) {
                    let sum = 0;
                    this.carList.forEach(item => {
                        if (this.checkAllGroup.indexOf(item.rowId) !== -1 && item.rowId.indexOf('**') !== -1) {
                            sum += (item.discountPrice * item.dishNum);
                        }
                    })
                    this.totalPrice = sum;
                }
            },
            // 结算
            handlePayment () {
                let cartIdArr = [];
                this.carList.forEach(item => {
                    if (this.checkAllGroup.indexOf(item.rowId) !== -1 && item.rowId.indexOf('**') !== -1) {
                        cartIdArr.push(item.cartId);
                    }
                })
                this.spinLoading = true;
                settlementCart(cartIdArr).then(res => {
                    this.spinLoading = false;
                    if (res.code === 1000 && res.data) {
                        this.showPayModal = true;
                        this.$nextTick(() => {
                            this.$refs.payCompRef.getOrderData(res.data);
                        })
                    }
                }).catch(() => {
                    this.spinLoading = false;
                })
            },
            // 删除
            handleDelete (item) {
                this.$Dialog
                    .confirm({
                        title: "是否确定删除购物车该菜肴？",
                    })
                    .then(() => {
                        this.spinLoading = true;
                        delCart([item.cartId]).then(res => {
                            this.spinLoading = false;
                            if (res.code === 1000) {
                                this.$Notify({ type: 'success', message: '删除成功！' });
                                this.getCarData();
                            }
                        }).catch(() => {
                            this.spinLoading = false;
                        })
                    })
                    .catch(() => { });
            },
            // 获取图片信息
            queryFileInfoData (filecodeArr) {
                this.loading = true;
                queryFileList(filecodeArr).then(res => {
                    if (res.code === 1000 && res.data) {
                        res.data.forEach(item => {
                            this.fileUrlObj[item.fileCode] = item.url;
                        })
                        this.$forceUpdate();
                        this.loading = false;
                    }
                }).catch(() => {
                    this.loading = false;
                })
            },
        }
    }
</script>

<style scoped lang="less">
    .myBtn {
        position: absolute;
        right: 15px;
        top: 12px;
        font-size: 18px;
    }
    .orderContent {
        padding: 8px;
        height: calc(100% - 46px);
        box-sizing: border-box;
        overflow: auto;
        background: #eee;
        .list-item {
            background: #fff;
            padding: 8px 8px 0 8px;
            box-sizing: border-box;
            & > .flexRow {
                padding-bottom: 8px;
            }
            /deep/.van-checkbox__icon .van-icon {
                width: 17px;
                height: 17px;
                line-height: 17px;
                margin-right: 3px;
                font-size: 13px;
            }
        }
        .list-head {
            margin-top: 8px;
        }
        img {
            width: 80px;
            height: 80px;
            margin: 0 8px;
        }
        .flexRow {
            display: flex;
            align-items: center;
            .con {
                flex: 1;
                overflow: hidden;
            }
        }
        .head {
            font-size: 12px;
            p {
                flex: 1;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                max-width: 200px;
                b {
                    font-size: 14px;
                }
            }
            span {
                margin-left: 10px;
            }
        }
        .dishName {
            p {
                flex: 1;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }
            span {
                color: #20bc12;
                font-size: 12px;
                margin-left: 10px;
            }
            .other {
                color: rgb(242, 36, 36);
            }
        }
        .priceNum {
            justify-content: space-between;
            color: #aaa;
            font-size: 11px;
            line-height: 30px;
            .price {
                color: rgb(242, 36, 36);
                margin-left: 10px;
                font-size: 12px;
            }
            span {
                margin-right: 5px;
            }
        }
        .action {
            justify-content: space-between;
            /deep/.stepBox {
                .van-stepper__input {
                    width: 60px;
                }
                .van-stepper__minus,
                .van-stepper__plus,
                .van-stepper__input {
                    height: 23px;
                    line-height: 23px;
                    font-size: 12px;
                }
            }
            a {
                font-size: 11px;
                border: 1px solid #ddd;
                padding: 3px 8px;
                border-radius: 10px;
                margin-left: 5px;
            }
        }
    }
    .bottomTip {
        .van-submit-bar__suffix-label {
            font-size: 11px;
            color: #aaa;
            float: left;
            line-height: 28px;
        }
        .van-submit-bar__button {
            width: auto;
        }
    }
</style>